package com.lccviolet;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author LiChaochao
 * @Date 2021/9/7 20:29
 * @Description ContainerNotSafeDemo 集合类不安全的问题，以ArrayList为例
 *
 * 补充：
 *      new一个ArrayList，底层new的是一个长度为10的Object类型的数组；
 *      扩容：Arrays.copyOf()方法
 */
public class ContainerNotSafeDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                list.add("a");
            }, String.valueOf(i)).start();
        }
        System.out.println(list);

        // 线程安全写法
        List<String> safeList1 = new Vector<>();
        List<String> safeList2 = Collections.synchronizedList(new ArrayList<>());
        List<String> safeList3 = new CopyOnWriteArrayList<>();

        Set<String> set = new CopyOnWriteArraySet<>();
        Map<String, Object> map = new ConcurrentHashMap<>();

    }
}
